package com.ssm.controller;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.ssm.base.controller.BaseController;
import com.ssm.base.model.Congiguration;
import com.ssm.base.model.Page;
import com.ssm.domain.User;
import com.ssm.service.IUserService;
import com.ssm.util.mybatis.ExampleType.Operation;
import com.ssm.util.mybatis.ExampleUtil;
import com.ssm.util.mybatis.FileUtil;

import tk.mybatis.mapper.entity.Config;
import tk.mybatis.mapper.entity.Example;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;

	/**
	 * baseservice 和 basemapper 里面单表的增删改查都有 而且特别多 单表操作全部不用写
	 * 
	 * mapper 和 实体 可以根据数据库直接逆向生成
	 * 
	 */

	/**
	 * 带分页的查找 一个最简单的例子
	 * 
	 * 
	 * http://localhost:8080/ssm/log/query?pageSize=2&pageNum=2%level=ss
	 * 
	 * 
	 * @Author 执笔
	 * @Date 2016年7月5日下午10:29:20
	 */
	@RequestMapping("query")
	public @ResponseBody PageInfo<User> query(Model model, User user, Page page) {
		Object example = ExampleUtil.getInstance().addParam("nickname", user.getNickname(), Operation.LIKE)//////// 工具里面有注释
				.addOrder("id")////// 排序 自己手写分组的时候分组也能用
				.getExample();
		PageInfo<User> pageInfo = userService.selectByExample(example, page);
		return pageInfo;
	}

	/**
	 * 登陆
	 * 
	 * @author suae
	 * @Date 2016年7月6日下午01:06
	 */
	@RequestMapping("login")
	public @ResponseBody User login(Model model, User user) {

		// Object object = ExampleUtil.getInstance()
		// .addParam("status",user.getNickname(),Operation.ISNULL)
		// .getExample();
		User newUser = userService.selectOne(user);
		return newUser;
	}

	/**
	 * 注册
	 * 
	 * @author suae
	 * @throws Exception
	 * @Date 2016年7月6日下午01:32
	 */
	@RequestMapping("regester")
	public @ResponseBody int regester(Model model, User user) throws Exception {
		 String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
	        Random random = new Random();  
	        StringBuffer sb = new StringBuffer();  
	          
	        for(int i = 0 ; i < 8; ++i){  
	            int number = random.nextInt(62);//[0,62)  
	              
	            sb.append(str.charAt(number));  
	        }  
		user.setId(sb.toString());
		String nickName = new String(user.getNickname().getBytes("utf-8"),"utf-8");;
//		user.setNickname(nickName);
		System.out.println(nickName + ":::"+user.getNickname());
		int statusCode = userService.insert(user);
		return statusCode;
	}

	/**
	 * 修改
	 * 
	 * @author suae
	 * @throws Exception
	 * @Date 2016年7月6日下午01:32
	 */
	@RequestMapping("update")
	public @ResponseBody int changeMessageOfUser(Model model, User user) throws Exception {
		int statusCode = userService.updateByPrimaryKey(user);
		return statusCode;
	}
	
	@RequestMapping("upload")
	public String upload(HttpServletRequest request,@RequestParam MultipartFile[] file) throws Exception{
		for(MultipartFile  f : file){
			
			String name = FileUtil.save(Congiguration.getString("file_path"), f);
//			Icon icon = new Icon();
//			icon.setDetail("头像");
//			icon.setName(name);
//			icon.setPath(name);
//			icon.setText("头像");
//			icon.setType(0);
//			iconService.insert(icon);
		}
		return "test";
	}
	
	@RequestMapping("download")    
    public ResponseEntity<byte[]> download() throws IOException {    
        String path=Congiguration.getString("file_path")+"0%Thumb%.bmp";  
        File file=new File(path);  
        HttpHeaders headers = new HttpHeaders();    
        String fileName=new String("0%Thumb%.bmp");//为了解决中文名称乱码问题  

        headers.setContentDispositionFormData("attachment", fileName);   
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                          headers, HttpStatus.CREATED);    
    }    

	
}
